package com.hotel.config.aliPay;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotel.config.websocket.WebSocketProcess;
import com.hotel.customersystem.enums.CusOrderStatus;
import com.hotel.customersystem.mapper.CustomerUserCouponMapper;
import com.hotel.customersystem.pojo.CustomerOrder;
import com.hotel.customersystem.pojo.CustomerUserCoupon;
import com.hotel.customersystem.service.CustomerOrderService;
import com.hotel.customersystem.service.CustomerUserCouponService;
import com.hotel.customersystem.service.OrderRedisService;
import com.hotel.hotelsystem.pojo.RoomInfo;
import com.hotel.hotelsystem.service.RoomInfoService;
import com.hotel.ordersystem.pojo.FlowList;
import com.hotel.ordersystem.service.FlowListService;
import org.elasticsearch.index.query.WrapperQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.DataLine;
import javax.websocket.server.PathParam;
import java.io.Console;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class AlipayController {

    @Resource
    private WebSocketProcess webSocketProcess; // 消息推送
    @Resource
    private FlowListService flowListService;
    @Resource
    private CustomerOrderService customerOrderService;
    @Resource
    private RoomInfoService roomInfoService;
    @Resource
    private CustomerUserCouponService customerUserCouponService;
    private AlipayUtil alipayUtil;

    @Resource
    private OrderRedisService orderRedisService;

    @Resource
    private CustomerUserCouponMapper couponMapper;

    @Autowired
    public void setAlipayUtil(AlipayUtil alipayUtil) {
        this.alipayUtil = alipayUtil;
    }

    @GetMapping("/")
    public String index(){
        return "index";
    }

    @GetMapping("/create")
    @ResponseBody
    @Transactional
    public String create( @PathParam("originPrice")String originPrice,
                          @PathParam("finalPrice") String finalPrice,
                          @PathParam("title") String title,
                          @PathParam("orderNo") String orderNo,
                          @PathParam("coupousANo")String coupousANo,
                          @PathParam("finalPrice")String coupousBNo,
                          Model model){
        String payNum = UUID.randomUUID().toString().replace("-","");
        FlowList flow = new FlowList();
        flow.setFlowNo(payNum);
        flow.setOrderNo(orderNo);
        if(!coupousANo.equals("null")) {
            flow.setDiscountConpousNo(Integer.valueOf(coupousANo));
            QueryWrapper<CustomerUserCoupon> wqA = new QueryWrapper<>();
            wqA.eq("coupon_no",coupousANo);
            CustomerUserCoupon couponA = customerUserCouponService.getOne(wqA);
            couponA.setCouponUseStatus(3);
            customerUserCouponService.updateById(couponA);
        }
        if(!coupousBNo.equals("null")) {
            flow.setFullConpousNo(Integer.valueOf(coupousBNo));
            QueryWrapper<CustomerUserCoupon> wqB = new QueryWrapper<>();
            wqB.eq("coupon_no",coupousBNo);
            CustomerUserCoupon couponB = customerUserCouponService.getOne(wqB);
            couponB.setCouponUseStatus(3);
            customerUserCouponService.updateById(couponB);
        }
        flow.setFinalAmount(Float.valueOf(finalPrice));
        flow.setOriginAmount(Float.valueOf(originPrice));
        flow.setPayState("0");
        flowListService.save(flow);



        String pay = alipayUtil.pay(payNum, finalPrice, title);
        model.addAttribute("form", pay);
        return pay;
    }

    @GetMapping("/return")
    @ResponseBody
    @Transactional
    public String returnNotice(String out_trade_no, String timestamp){
        QueryWrapper<FlowList> wq = new QueryWrapper<>();
        wq.eq("flow_no",out_trade_no);
        FlowList flow = flowListService.getOne(wq);
        System.out.println("*******************************************\n"+flow);
        String orderNo = flow.getOrderNo();
        QueryWrapper<CustomerOrder> wq1 = new QueryWrapper<>();
        wq1.eq("order_no",orderNo);
        CustomerOrder customerOrder = customerOrderService.getOne(wq1);
        System.out.println("*******************************************\n"+customerOrder);
        customerOrder.setOrderStatus(3);
        boolean b = customerOrderService.updateById(customerOrder);
        //删除redis存储的订单
        orderRedisService.getOrderByIdFromRedis(customerOrder.getUserId(),customerOrder.getOrderNo());

        //更改优惠券状态
        if (customerOrder.getStandby01()!=null&&customerOrder.getStandby01().equals("null")&&customerOrder.getStandby01().equals("")){
            CustomerUserCoupon byCouponNo = couponMapper.getByCouponNo(customerOrder.getStandby01());
            if (byCouponNo.getCouponUseStatus()==3){
                byCouponNo.setState(1);
            }
            couponMapper.updateById(byCouponNo);
        }
        if (customerOrder.getStandby02()!=null&&customerOrder.getStandby02().equals("null")&&customerOrder.getStandby02().equals("")){
            CustomerUserCoupon byCouponNo = couponMapper.getByCouponNo(customerOrder.getStandby02());
            if (byCouponNo.getCouponUseStatus()==3){
                byCouponNo.setState(1);
            }
            couponMapper.updateById(byCouponNo);
        }

        String userAdmin = String.valueOf(customerOrder.getUserId());
        flow.setPayState("1");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        flow.setPayTime(LocalDateTime.parse(timestamp,formatter));
        flowListService.updateById(flow);
        Map<String,Object> message =new HashMap<>();
        message.put("orderNo",customerOrder.getOrderNo());
        message.put("flowNo",flow.getFlowNo());
        message.put("paytime",flow.getPayTime());
        message.put("finalPrice","￥"+flow.getFinalAmount());
        flowListService.updateById(flow);

        System.out.println("支付成功");
        try {
            // 消息推送  单发
            webSocketProcess.sendMessage(userAdmin, JSON.toJSONString(message));
            // 群发
            //webSocketProcess.sendAllMessage("msg");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "已支付完成，请关闭此页面";
    }

    @PostMapping("/notify")
    public void notifyUrl(String trade_no, String total_amount, String trade_status){
        System.err.println("支付宝订单编号：" + trade_no + ", 订单金额： " + total_amount + ",订单状态：" + trade_status);
    }
}
